package com.fry.mall.wallet.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fry.mall.wallet.dto.RefundDTO;
import com.fry.mall.wallet.dto.UserConsumeDTO;
import com.fry.mall.wallet.dto.UserWalletDTO;
import com.fry.mall.wallet.entity.UserWalletLog;
import com.fry.mall.wallet.interceptor.WalletInterceptor;
import com.fry.mall.wallet.response.ResponseResult;
import com.fry.mall.wallet.service.UserWalletLogService;
import com.fry.mall.wallet.service.UserWalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 用户钱包控制层
 *
 * @Author: FRY
 * @CreateTime: 2023-03-02  21:30
 */
@RestController
@RequestMapping("/api/wallet")
public class UserWalletController {

    @Autowired
    private UserWalletService userWalletService;

    @Autowired
    private UserWalletLogService userWalletLogService;

    /**
     * 获取登陆用户钱包余额等信息
     *
     * @author: FRY
     * @date: 2023/03/02 22:43
     * @return: ResponseResult<UserWalletDTO>
     */
    @GetMapping
    public ResponseResult<UserWalletDTO> getUserWalletBalance() {
        UserWalletDTO userWalletDTO = userWalletService.getUserWalletBalance();
        if (userWalletDTO != null) {
            return ResponseResult.success(userWalletDTO);
        }
        return ResponseResult.showFailMsg("用户登陆异常");
    }

    /**
     * 用户消费接口
     *
     * @author: FRY
     * @date: 2023/03/03 0:18
     * @param: userConsumeDTO
     * @return: ResponseResult<Boolean>
     */
    @PostMapping("/consume")
    public ResponseResult<Boolean> userConsume(UserConsumeDTO userConsumeDTO) {

        // 假设这里是用户消费时使用的支付平台接口
        Boolean sign = Boolean.valueOf("https://pay.com");

        // 这里保存订单信息，并获得订单id,以及订单号，最后赋值到userConsumeDTO中
        Boolean order = Boolean.valueOf("orderFeignService.saveOrderInfo");

        if (sign && order) {
            Boolean s = userWalletService.dealConsumeOrder(userConsumeDTO);
            return ResponseResult.success(s);
        }

        return ResponseResult.showFailMsg("消费失败");
    }

    /**
     * 用户退款接口
     *
     * @author: FRY
     * @date: 2023/03/03 0:18
     * @param: refundDTO
     * @return: ResponseResult<Boolean>
     */
    @PostMapping("/refund")
    public ResponseResult<String> refundBalance(RefundDTO refundDTO) {

        return userWalletService.dealRefund(refundDTO);
    }

    /**
     * 获取用户账户钱包的变动明细数据
     *
     * @author: FRY
     * @date: 2023/03/03 1:07
     * @return: ResponseResult<List < UserWalletLog>>
     */
    @GetMapping("/changes")
    public ResponseResult<List<UserWalletLog>> getBalanceChanges() {
        String userId = WalletInterceptor.threadLocal.get();
        List<UserWalletLog> userWalletLogList = userWalletLogService.list(new QueryWrapper<UserWalletLog>().eq("user_uuid", userId));

        return ResponseResult.success(userWalletLogList);
    }
}
